import { createRouter, createWebHistory } from 'vue-router'
import Login from '../views/Login.vue'
import Register from '../views/Register.vue'
import ChildList from '../views/ChildList.vue'
import HabitList from '../views/HabitList.vue'
import Timeline from '../views/Timeline.vue'
import Calendar from '../views/Calendar.vue'
import Statistics from '../views/Statistics.vue'
import PointsExchange from '../views/PointsExchange.vue'
import NotFound from '../views/NotFound.vue'

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/register',
    name: 'Register',
    component: Register
  },
  {
    path: '/children',
    name: 'ChildList',
    component: ChildList
  },
  {
    path: '/habits/:childId',
    name: 'HabitList',
    component: HabitList,
    props: true
  },
  {
    path: '/timeline/:childId',
    name: 'Timeline',
    component: Timeline
  },
  {
    path: '/calendar/:childId',
    name: 'Calendar',
    component: Calendar
  },
  {
    path: '/statistics/:childId',
    name: 'Statistics',
    component: Statistics
  },
  {
    path: '/points/:childId',
    name: 'PointsExchange',
    component: PointsExchange
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: NotFound
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 简化路由守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  if (!token && !['/login', '/register'].includes(to.path)) {
    next('/login')
  } else {
    next()
  }
})

// 添加错误处理
router.onError((error) => {
  console.error('路由错误:', error)
})

export default router 